package middleware

import (
    "context"
    "github.com/labstack/gommon/log"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    "longmen/server/pkg/common/helper/util"
    "time"
)

type SportRequestLimit struct {
    Limit *util.RequestLimitService
}

func NewSportRequestLimit() *SportRequestLimit {
    r := util.NewRequestLimitService(time.Second, 75)
    return &SportRequestLimit{
        Limit: r,
    }
}

func (r *SportRequestLimit) RequestLimit(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
    if !r.Limit.IsAvailable() {
        log.Errorf("SportRequestLimit 每秒请求超出限制,当前访问次数:%d", r.Limit.ReqCount)
        return nil, status.Errorf(codes.Unauthenticated, "每秒请求超出限制,当前访问次数")
    }
    r.Limit.Increase()
    return handler(ctx, req)
}
